package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
//SQLIntegrityConstraintViolationException 异常
//Duplicate entry 'wang' for key 'idx_username 异常信息
@RestControllerAdvice(annotations ={RestController.class,Controller.class} )
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exception(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            return R.error(split[2]+"已存在");
        }
        e.printStackTrace();
        return R.error("未知错误");
    }

//    @ExceptionHandler(CustomException.class)//声明是一个异常捕捉器,里面的参数是捕获异常的类
    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException e){
        return R.error(e.getMessage());
    }
}
